package br.com.social.mobile.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.transform.Transformers;

import br.com.social.mobile.dto.ChatMessageDto;
import br.com.social.mobile.entities.ChatMessage;


public class ChatMessageDAO extends GenericDAO<ChatMessage>{

	private Logger logger = Logger.getLogger(ChatMessage.class);

	@SuppressWarnings("unchecked")
	public List<ChatMessageDto> getListChatMessage(Long nuIdUser) {
		
		List<ChatMessageDto> listMessage = null;
		
		try {
			createEntityManager();
			
	        Session session = (Session) entityManager.getDelegate();  
	        Query q = 
	        	session
	        		.createSQLQuery("select cm.NU_ID as nuIdMessage, " 
	        						+ "cm.ID_CHAT as nuIdChat, " 
	        						+ "cm.DS_MESSAGE as dsMessage, "  
	        						+ "cm.DT_MESSAGE as dtMessage, "  
									+ "cm.ID_USER_SEND as nuIdUserSend, "
									+ "p1.DS_NAME as dsNameProfileSend, "
									+ "u1.DS_NAME as dsNameUserSend, "  
									+ "u1.DS_IMG_USER as dsFotoUserSend, " 
									+ "cg2.NU_ID_USER as nuIdUserReceive, "
								    + "p2.DS_NAME as dsNameProfileReceive, "
									+ "u2.DS_NAME as dsNameUserReceive, "  
									+ "u2.DS_IMG_USER as dsFotoUserReceive " 
							+ "from tb_chat_group cg1 " 
							+ "inner join tb_chat_message cm on (cm.ID_CHAT = cg1.NU_ID_CHAT) "
							+ "inner join  tb_chat_group cg2 on (cg2.NU_ID_CHAT = cg1.NU_ID_CHAT) "
							+ "inner join tb_user u1 on (cm.ID_USER_SEND = u1.NU_ID) "
							+ "inner join tb_user u2  on (cg2.NU_ID_USER = u2.NU_ID) "
							+ "inner join tb_profile p1 on (p1.NU_ID = u1.NU_ID_PROFILE) "
							+ "inner join tb_profile p2 on (p2.NU_ID = u2.NU_ID_PROFILE) "
							+ "where cg1.NU_ID_USER = :nuIdUser "
							+ "and cg2.NU_ID_USER <> :nuIdUser "
							+ "order by cm.dt_message desc limit 1;")
				.addScalar("nuIdMessage")
				.addScalar("nuIdChat")
				.addScalar("dsMessage")
				.addScalar("dtMessage")
				.addScalar("nuIdUserSend")
				.addScalar("dsNameProfileSend")
				.addScalar("dsNameUserSend")
				.addScalar("dsFotoUserSend")
				.addScalar("nuIdUserReceive")
				.addScalar("dsNameProfileReceive")
				.addScalar("dsNameUserReceive")
				.addScalar("dsFotoUserReceive")				
                .setResultTransformer(Transformers.aliasToBean(ChatMessageDto.class)) 
				.setParameter("nuIdUser", nuIdUser);

			listMessage = q.list();

		} catch (Exception e) {
			logger.error(e);
		}
		
		return listMessage;

	}	



}
